package com.ruoyi.erp.controller;

import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.erp.domain.*;
import com.ruoyi.erp.util.api;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.erp.service.IBzFaVouchersDetailService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 资产变动Controller
 *
 * @author ztj
 * @date 2023-04-18
 */
@RestController
@RequestMapping("/erp/cardsup")
public class BzFaVouchersDetailController extends BaseController {
    @Autowired
    private IBzFaVouchersDetailService bzFaVouchersDetailService;
    @Autowired
    private api api;

    /**
     * 查询资产变动列表
     */
    @PreAuthorize("@ss.hasPermi('erp:cardsup:list')")
    @GetMapping("/list")
    public TableDataInfo list(BzFaVouchersDetail bzFaVouchersDetail) {
        startPage();
        List<BzFaVouchersDetail> list = bzFaVouchersDetailService.selectBzFaVouchersDetailList(bzFaVouchersDetail);
        return getDataTable(list);
    }

    /**
     * 资产同步
     */
    @PreAuthorize("@ss.hasPermi('erp:cards:add')")
    @Log(title = "资产变动同步", businessType = BusinessType.IMPORT)
    @GetMapping("/sync/{ids}")
    public AjaxResult faSync(@PathVariable Long[] ids) {
//        int isS = bzFaVouchersDetailService.updateBzFaVouchersDetailIds(ids);
//        if (isS > 0) new Thread(() -> faPush(ids)).start();
        return faPush(ids);
//        return toAjax(isS);
    }

    /**
     * 资产推送
     */
    @PreAuthorize("@ss.hasPermi('erp:cards:add')")
    @Log(title = "资产变动推送", businessType = BusinessType.IMPORT)
    @GetMapping("/push/{ids}")
    public AjaxResult faPush(@PathVariable Long[] ids) {
        List<BzFaVouchersDetail> list = bzFaVouchersDetailService.selectBzFaVouchersDetailByIds(ids);
        Map<String, String> heads = new HashMap<>();
        heads.put("Content-Type", "application/json;charset=UTF-8");
        List<String> applyId = new ArrayList<>();
        list.forEach(item -> {
            if (!applyId.contains(item.getBillCode())) {
                applyId.add(item.getBillCode());
            }

        });
        applyId.forEach(item -> {
            BzFaCardsUpParam upParam = new BzFaCardsUpParam();
            upParam.setApplyId(item);
            upParam.setOptUserName(getLoginUser().getUsername());
            List<BzFaCardsUpParam.RowsBean> rowsBeans = new ArrayList<>();
            List<Long> idsRow = new ArrayList<>();
            list.forEach(card -> {
                if (item.equals(card.getBillCode())) {
                    upParam.setOptUserName(card.getsOperator());
                    BzFaCardsUpParam.RowsBean rowsBean = new BzFaCardsUpParam.RowsBean();
                    rowsBean.setOptFlag("1");
                    rowsBean.setFineAssetCode(card.getsAssetNum());
                    rowsBean.setChangeType(card.getiVoucherType());
                    rowsBeans.add(rowsBean);
                    idsRow.add(card.getId());
                }
            });
            upParam.setRows(rowsBeans);
            logger.debug(JSONUtil.toJsonStr(upParam));
            HttpResponse response = HttpRequest.post(api.getUpFa())
                    .headerMap(heads, false)
                    .body(String.valueOf(JSONUtil.toJsonStr(upParam)))
                    .timeout(5 * 60 * 1000)
                    .execute();
            logger.debug(response.body());
            ResultData resultData = JSONUtil.toBean(response.body(), ResultData.class);
            if (resultData.getErrorcode() == 0) {
                bzFaVouchersDetailService.updateBzFaVouchersDetailIds(idsRow.toArray(new Long[list.size()]));
            } else {
                bzFaVouchersDetailService.updateBzFaVouchersDetailIdsFail(idsRow.toArray(new Long[list.size()]));
            }
        });
//        BzFaCardsParam param = new BzFaCardsParam();
//        param.setBill_date(DateUtil.format(new Date(), "yyyy-MM-dd"));
//        param.setBill_iOptType("变动");
//        List<Bills> bills = new ArrayList<>();
//        Bills bill = new Bills();
//        bill.setBill_code(UUID.fastUUID().toString());
//        bill.setVouchers(BeanUtil.copyToList(list, Object.class));
//        bills.add(bill);
//        param.setBills(bills);

        return toAjax(1);
    }

    @PostMapping("/pushNotice")
    public AjaxResult pushNotice(@RequestBody BzFaCardsParam param) {
        logger.debug(JSONUtil.toJsonStr(param));
        List<BzFaVouchersDetail> returnNotice = new ArrayList<>();
        param.getBills().forEach(item -> {
            List<BzFaVouchersDetail> list = BeanUtil.copyToList(item.getVouchers(), BzFaVouchersDetail.class);
            list.forEach(cards -> {
                cards.setBillCode(item.getBill_code());
                if (StringUtils.isNotEmpty(cards.getsSiteAfter())) {
                    bzFaVouchersDetailService.updateBzFaVouchersDetailIdErp(cards);
                }
                if (bzFaVouchersDetailService.insertBzFaVouchersDetail(cards) == 1) {
                    returnNotice.add(cards);
                }
            });
        });

        return success(returnNotice);
    }

    /**
     * 导出资产变动列表
     */
    @PreAuthorize("@ss.hasPermi('erp:cardsup:export')")
    @Log(title = "资产变动", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BzFaVouchersDetail bzFaVouchersDetail) {
        List<BzFaVouchersDetail> list = bzFaVouchersDetailService.selectBzFaVouchersDetailList(bzFaVouchersDetail);
        ExcelUtil<BzFaVouchersDetail> util = new ExcelUtil<BzFaVouchersDetail>(BzFaVouchersDetail.class);
        util.exportExcel(response, list, "资产变动数据");
    }

    /**
     * 获取资产变动详细信息
     */
    @PreAuthorize("@ss.hasPermi('erp:cardsup:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(bzFaVouchersDetailService.selectBzFaVouchersDetailById(id));
    }

    /**
     * 新增资产变动
     */
    @PreAuthorize("@ss.hasPermi('erp:cardsup:add')")
    @Log(title = "资产变动", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BzFaVouchersDetail bzFaVouchersDetail) {
        return toAjax(bzFaVouchersDetailService.insertBzFaVouchersDetail(bzFaVouchersDetail));
    }

    /**
     * 修改资产变动
     */
    @PreAuthorize("@ss.hasPermi('erp:cardsup:edit')")
    @Log(title = "资产变动", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BzFaVouchersDetail bzFaVouchersDetail) {
        return toAjax(bzFaVouchersDetailService.updateBzFaVouchersDetail(bzFaVouchersDetail));
    }

    /**
     * 删除资产变动
     */
    @PreAuthorize("@ss.hasPermi('erp:cardsup:remove')")
    @Log(title = "资产变动", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(bzFaVouchersDetailService.deleteBzFaVouchersDetailByIds(ids));
    }
}
